"use strict";

var libs = {
    observer: {},
    go: function go() {
        var $this = $(this),
            url = $this.attr("data-url");

        var request = libs.getRequest();
        if (request['page']) {
            history.pushState({}, "蒙自公安大数据智能作战平台", window.location.pathname);
        }
        sessionStorage.appUrl = url;
        $('#sys-main').empty().load(url + ".html");
        libs.menuActive();
    },
    _blank: function blank() {
        var url = $(this).attr("data-url");
        window.open("index.html?page=" + url);
    },
    blank: function blank(url, o, host) {
        var params = "";
        for (var i in o) {
            params += "&" + i + "=" + o[i];
        }
        window.open(host + "?page=" + url + params);
    },
    menuActive: function menuActive(nowPage) {
        nowPage = nowPage ? nowPage : sessionStorage.appUrl ? sessionStorage.appUrl : "";
        var menuStatus = false;

        setTimeout(function () {
            $("#sys-menu ul.sys-menu-child li a").each(function () {
                var url = $(this).attr('data-url');
                if (nowPage === url) {
                    $("#sys-menu li").removeClass("active");
                    $(this).parent().parent().parent().addClass('active');
                    $(this).parent().addClass('active');
                    menuStatus = true;
                }
            });
            if (!menuStatus) {
                $("#sys-menu .parentMenu").each(function () {
                    var url = $(this).attr('data-url');
                    if (nowPage === url) {
                        $("#sys-menu li").removeClass("active");
                        $(this).parent().addClass('active');
                        menuStatus = true;
                    }
                });
            }
            if (menuStatus) {
                $(".curLine").css({
                    "width": $("#sys-menu > ul > li.active").width(),
                    "left": $("#sys-menu > ul > li.active").position().left
                });
            } else {
                var jqyp = ['views/analysisApp/alarm/alarm-step2', 'views/analysisApp/alarm/alarm-step3', 'views/analysisApp/alarm/alarm-step4', 'views/analysisApp/alarm/alarm-step5', 'views/analysisApp/alarm/alarm-step6'];
                if (jqyp.indexOf(nowPage) > -1) {
                    nowPage = "views/analysisApp/alarm/index";
                }
                var lflk = ['views/analysisApp/area/index', 'views/analysisApp/area/area-aqlk'];
                if (lflk.indexOf(nowPage) > -1) {
                    nowPage = "views/analysisApp/area/area-pre";
                }
                var gjfx = ['views/analysisApp/tools/tools-track-device', 'views/analysisApp/tools/tools-track-personal'];
                if (gjfx.indexOf(nowPage) > -1) {
                    nowPage = "views/analysisApp/tools/tools-track";
                }
                libs.menuActive(nowPage);
                return;
            }
            $("#sys-menu").on("mouseover", "li", function () {
                $(".curLine").stop(true).animate({
                    left: $(this).position().left,
                    width: $(this).width()
                }, 200);
            });

            $("#sys-menu").on("mouseout", "li", function () {
                $(".curLine").stop(true).animate({
                    left: $("#sys-menu > ul > li.active").length > 0 ? $("#sys-menu > ul > li.active").position().left : 0,
                    width: $("#sys-menu > ul > li.active").width()
                }, 200);
            });
        }, 500);
    },
    setPublicLink: function setPublicLink(data) {
        _.map(data, function (o) {
            if (o.systemIdentifier == "access") libs.access = o.systemUrl; //数据采集系统
            if (o.systemIdentifier == "cleaning") libs.resource = o.systemUrl; //数据资源系统
            if (o.systemIdentifier == "exch") libs.share = o.systemUrl; //共享交换系统
            if (o.systemIdentifier == "analysis") libs.analysis = o.systemUrl; //智能作战系统
            if (o.systemIdentifier == "index") libs.bigdata = o.systemUrl; //大数据平台首页
        });
    },
    fileBtn: function fileBtn(i) {
        if ($("#readFile").length < 1) {
            $("body").append("<input type='file' id='readFile' style='opacity:0'>");
        }
        $("#readFile").trigger("click");

        document.getElementById('readFile').addEventListener('change', function () {
            libs.readFile(this, function (data) {
                // var data = data.replace('\t', ',').replace('\r', ',').replace('\n', ',');
                var data = data.replace(/\r\n/g, ',');
                data = data.replace(/\n/g, ',');
                i.val(data);
            }, function () {
                alert('解析文件出错');
            });
        });
    },
    readFile: function readFile(input, sc, ec) {
        //支持chrome IE10
        if (window.FileReader) {
            var file = input.files[0];
            filename = file.name.split(".")[0];
            var reader = new FileReader();
            reader.onload = function () {
                sc(this.result);
            };
            reader.readAsText(file, 'gb2312');
        }
        //支持IE 7 8 9 10
        else if (typeof window.ActiveXObject != 'undefined') {
                var xmlDoc;
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = false;
                xmlDoc.load(input.value);
                sc(xmlDoc);
            }
            //支持FF
            else if (document.implementation && document.implementation.createDocument) {
                    var xmlDoc;
                    xmlDoc = document.implementation.createDocument("", "", null);
                    xmlDoc.async = false;
                    xmlDoc.load(input.value);
                    sc(xmlDoc);
                } else {
                    ec();
                }
    },
    uploadFile: function uploadFile(obj) {
        if ($("#uploadFile").length > 0) {
            $("#uploadFile").remove();
        }
        $("body").append("<input type='file' id='uploadFile' style='opacity:0'>");
        $("#uploadFile").trigger("click");

        $('#uploadFile').on('change', function () {
            var _files = this.files;
            var reader = new FileReader();
            var step = 100 * 1024;
            var total = _files[0].size;
            var cuLoaded = 0;
            var uid = "";
            var stop = {};
            function startUpload(start) {
                $(obj.submit).attr("readonly", true);
                uploadFile(start, uid, function (res) {
                    if (stop[uid]) return;
                    cuLoaded = res.data.start;
                    if (obj.hock) {
                        obj.hock({ uid: uid, start: start, total: total, file: _files[0], stop: stop });
                    }
                    //如果没有读完，继续
                    if (cuLoaded < total) {
                        startUpload(cuLoaded);
                    } else {
                        cuLoaded = total;
                        if (obj.callback) {
                            obj.callback(res.data, { uid: uid });
                        }
                    }
                });
            }
            //指定开始位置，分块读取文件
            function readBlob(start) {
                //指定开始位置和结束位置读取文件
                var blob = _files[0].slice(start, start + step);
                reader.readAsArrayBuffer(blob);
            }
            //开始读取
            function uploadFile(startIndex, uid, onSuccess) {
                var blob = sliceFile(_files[0], startIndex, startIndex + step);
                //提交到服务器
                if (!_files.length) return;
                if (_files.length === 1) {
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', obj.api + "&token=" + uid + "&fileName=" + _files[0].name + "&apiType=" + obj.apiType);
                    var range = "bytes " + startIndex + "-" + (startIndex + step) + "/" + total;
                    xhr.setRequestHeader("Content-Range", range);
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            if (xhr.responseText.substr(0, 20).indexOf("<!DOCTYPE html>") != -1) {
                                _as.jAlert("<p>对不起，服务器接口出错！请联系技术人员！</p>");
                                throw "对不起，服务器接口出错！";
                            }
                            var result = JSON.parse(xhr.responseText);
                            if (Number(result.status.code) !== 200) {
                                _as.jAlert(result.status.message);
                                throw result.status.message;
                            }
                            if (onSuccess) onSuccess(result);
                        }
                    };
                    xhr.send(blob);
                } else {}
            }
            function sliceFile(f, startPos, endPos) {
                startPos = startPos || 0;
                endPos = endPos || 0;
                return f.slice ? f.slice(startPos, endPos) : f.webkitSlice ? f.webkitSlice(startPos, endPos) : f.mozSlice ? f.mozSlice(startPos, endPos) : f;
            }
            function getToken() {
                //提交到服务器
                if (!_files.length) return;
                if (_files.length === 1) {
                    var xhr = new XMLHttpRequest();
                    xhr.open('GET', obj.token + "&fileName=" + _files[0].name + "&fileSize=" + total + "&apiType=" + obj.apiType);
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            if (xhr.responseText.substr(0, 20).indexOf("<!DOCTYPE html>") != -1) {
                                _as.jAlert("<p>对不起，服务器接口出错！请联系技术人员！</p>");
                                throw "对不起，服务器接口出错！";
                            }
                            var result = JSON.parse(xhr.responseText);
                            if (Number(result.status.code) !== 200) {
                                _as.jAlert(result.status.message);
                                throw result.status.message;
                            }
                            uid = result.data.token;
                            stop[uid] = false;
                            getStart();
                        }
                    };
                    xhr.send();
                } else {}
            }
            function getStart() {
                //提交到服务器
                if (!_files.length) return;
                if (_files.length === 1) {
                    var xhr = new XMLHttpRequest();
                    xhr.open('GET', obj.get + "&token=" + uid + "&fileName=" + _files[0].name + "&fileSize=" + total + "&apiType=" + obj.apiType);
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            if (xhr.responseText.substr(0, 20).indexOf("<!DOCTYPE html>") != -1) {
                                _as.jAlert("<p>对不起，服务器接口出错！请联系技术人员！</p>");
                                throw "对不起，服务器接口出错！";
                            }
                            var result = JSON.parse(xhr.responseText);
                            if (Number(result.status.code) !== 200) {
                                _as.jAlert(result.status.message);
                                throw result.status.message;
                            }
                            startUpload(result.data.start);
                        }
                    };
                    xhr.send();
                } else {}
            }
            getToken();
        });
    },
    checkIdCard: function checkIdCard(code, msg) {
        var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " };
        var tip = "";
        var pass = true;

        if (!code) {
            tip = msg + "身份证号不能为空";
            pass = false;
        } else if (!/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[120])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
            tip = msg + "身份证号格式错误";
            pass = false;
        } else if (!city[code.substr(0, 2)]) {
            tip = msg + "身份证地址编码错误";
            pass = false;
        } else {
            //18位身份证需要验证最后一位校验位
            if (code.length == 18) {
                code = code.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                //校验位
                var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++) {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                var last = parity[sum % 11];
                if (parity[sum % 11] != code[17]) {
                    tip = msg + "身份证校验位错误";
                    pass = false;
                }
            }
        }
        if (!pass) {
            _as.jAlert("<p>" + tip + "</p>");
            throw "错误的身份证信息";
        }
        return pass;
    },
    checkPhone: function checkPhone(code) {
        if (code == "") return;
        if (/^\s+$/.test(code)) {
            return;
        }
        var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        if (!myreg.test(code)) {
            _as.jAlert("<p>请输入有效的手机号码！</p>");
            throw "错误的手机号码";
        }
        return true;
    },
    showLoading: function showLoading() {
        if ($("#loading").length < 1) {
            var box = "<div class=\"alertLoading\" id=\"loading\">";
            box += "<div class=\"layerbg\"></div>";
            box += "<div class=\"layerbox\">";
            box += "<img src=\"./assets/images/loading.gif\">";
            box += "</div>";
            box += "</div>";
            $(box).appendTo("body");
        }
        $("#loading").show();
    },
    getRequest: function getRequest() {
        var url = location.search; //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") !== -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    },
    showText: function showText(obj) {
        var self = this;
        obj.addEventListener("mouseover", function () {
            self.bindMove(obj.text);
        });
        obj.addEventListener("mouseout", function () {
            $(".mapshow").hide();
            self.unBindMove();
        });
    },
    showText2: function showText(obj) {
        var self = this;
        obj.addEventListener("mouseover", function (d) {
            if(d.point.name){
                self.bindMove(d.point.name);
            }
        });
        obj.addEventListener("mouseout", function () {
            $(".mapshow").hide();
            self.unBindMove();
        });
    },
    bindMove: function bindMove(text) {
        var self = this;
        $(".mapshow").remove();
        $("body").append("\n            <div class=\"mapshow\">\n                <h3>" + text + "</h3>\n            </div>\n        ");
        var alert = $(".mapshow");
        alert.show();
        window.setCapture ? (
        //捕捉焦点 
        window.setCapture(),
        //设置事件 
        window.onmousemove = function (ev) {
            self.mouseMove(ev || event);
        }) :
        //绑定事件 
        $(document).bind("mousemove", self.mouseMove);
    },
    mouseMove: function mouseMove(event) {
        var x = event.pageX + 12;
        var y = event.pageY + 20;
        // 拖拽元素随鼠标移动
        $(".mapshow").css({ left: x + 'px', top: y + 'px' });
    },
    unBindMove: function unBindMove(event) {
        window.releaseCapture ? (
        //释放焦点 
        window.releaseCapture(),
        //移除事件 
        window.onmousemove = null) :
        //卸载事件 
        $(document).unbind("mousemove", self.mouseMove);
        $(".mapshow").remove();
    },
    bindDate: function bindDate(el, status) {
        var showTime = status ? false : true;
        var format = status ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss';
        var ranges = status ? {
            '今日': [moment().startOf('day')],
            '昨日': [moment().subtract('days', 1).startOf('day')]
        } : {
            '今日': [moment().startOf('day')],
            '昨日': [moment().subtract('days', 1).startOf('day')],
            '现在': [moment().startOf('second')]
        };
        $(el).daterangepicker({
            singleDatePicker: true,
            showDropdowns: true,
            timePicker: showTime,
            timePickerIncrement: 1,
            timePicker12Hour: false,
            startDate: moment().startOf('day'),
            format: format,
            ranges: ranges
        });
    },
    loadComp: function loadComp(url, cb) {
        $.get(url, cb);
    },
    on: function on(name, fn) {
        this.observer[name] = fn;
    },
    emit: function emit(fn, args) {
        if (this.observer[fn]) {
            this.observer[fn].apply(this, args);
        }
    },
    destroyed: function destroyed(fn) {
        delete this.observer[fn];
    }
};